package com.yequan.socket.mutilthread;

import java.io.*;
import java.net.Socket;

/**
 * @author : Administrator
 * @date : 2020/2/14
 */
public class Client {


    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            service();
            Thread.sleep(1000);
        }
    }

    private static void service() {
        try {
            //1.创建socket客户端,指定服务器地址和端口
            Socket socket = new Socket("192.168.0.2", 8888);

            //2.获取输出流,向服务器发送消息
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);
            printWriter.write("山川异域,日月同天");
            printWriter.flush();
            socket.shutdownOutput();

            //3.获取输入流,读取服务器响应的消息
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line = null;
            StringBuffer stringBuffer = new StringBuffer();
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            System.out.println("服务器消息: " + stringBuffer.toString());

            //4.关闭资源
            bufferedReader.close();
            inputStreamReader.close();
            printWriter.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
